﻿@Cofe ?= {}

$ = jQuery
utils = Cofe.utils

selectSupport = 

  initSingleSelect : (entryItemList) ->
    #@bind("rendering", (sender, entryItems) ->
    #   for entryItem in entryItems
    #     entryItem.unbind("clicked")
    #)

    #@bind("rendered", (sender, entryItems) ->
    #   dis = @
    #   for entryItem in entryItems
    #     entryItem.bind("clicked", (entryItem) =>
    #       @trigger("selected", dis, [ entryItem ])
    #       item.el.removeClass("ui-selected") for item in dis.allEntryItems
    #       entryItem.el.addClass("ui-selected")           
    #     )
    #)

    @bind("itemAdded", (sender, entryItem, idx) ->
       dis = @
       entryItem.bind("clicked", (entryItem) =>
         @trigger("selected", dis, [ entryItem ])
         item.el.removeClass("ui-selected") for item in dis.allEntryItems
         entryItem.el.addClass("ui-selected")           
       )
    )

    @bind("itemRemoved", (sender, entryItem, idx) ->
       entryItem.unbind("clicked")
    )

  initMultiSelect : (entryItemList) ->
    dis = @
    @el.selectable({ 
       filter: @childTag
       stop: () ->
         selectedItems = []
         selectedIdx = ($(ei).index() for ei in $(".ui-selected", entryItemList.el))
         selectedItems = (dis.allEntryItems[idx] for idx in selectedIdx)
         dis.trigger("selected", dis, selectedItems)
    })
    #http://forum.jquery.com/topic/selectable-dosn-t-fire-click-event
    #@el.selectable( "option", "distance", 30 )
    @el.selectable({ cancel: "a,.label" })
  

Cofe.selectSupport = selectSupport